/*
-----------------------------------------------------------------------------
This source file is part of as4game
    (ActionScript For Game Engine)
For the latest info, see http://as4game.googlecode.com

Copyright (c) 2000-2011 Hproof Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
package org.as4game.render3d
{
	import flash.display.Stage;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DCompareMode;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DTriangleFace;
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	
	import org.as4game.scene3d.Camera;
	import org.as4game.scene3d.MovableObject;
	import org.as4game.scene3d.Scene;

	/**
	 * Render3D
	 */
	public class Render3D
	{
		private var _createCallback:Function;
		private var _stage3D:Stage3D;
		private var _context3D:Context3D;
		
		public var num_triangle:uint;
		public var num_pass:uint;
		
		/**
		 * 构造函数
		 * @param stage 如果非空, 则建立
		 */
		public function Render3D(stage:Stage=null, callback:Function=null, width:int=0, height:int=0):void{
			if( stage!=null ){
				create( stage, callback, width, height);
			}
		}
		
		/**
		 * 视区, 如果视区为空, 则不在屏幕上显示
		 */
		public function get viewport():Rectangle{
			return _stage3D.viewPort;
		}
		public function set viewport( value:Rectangle ):void{
			_stage3D.viewPort = value;
		}
		
		/**
		 * 3D 设备
		 */
		public function get context3D():Context3D{
			return _context3D;
		}
		
		/**
		 * 建立设备
		 * @param callback 建立成功后的回调函数, function callback(render3D:Render3D):void;
		 */
		public function create( stage:Stage, callback:Function, width:int=0, height:int=0 ):void{
			dispose();
			
			var stage3ds:Vector.<Stage3D> = stage.stage3Ds;
			for(var i:int=0; i<stage3ds.length; i++){
				if( stage3ds[i].context3D == null ){
					_stage3D = stage3ds[i];
					break;
				}
			}
			
			if( _stage3D == null ){
				throw new Error("没有空闲的设备");
			} 
			
			_createCallback = callback;
			_stage3D.viewPort = new Rectangle ( 0, 0, width, height );
			_stage3D.addEventListener( Event.CONTEXT3D_CREATE , _onContext3DCreate ); 			
			_stage3D.requestContext3D( Context3DRenderMode.AUTO );
		}
		private function _onContext3DCreate(e:Event):void{
			_stage3D.removeEventListener( Event.CONTEXT3D_CREATE, _onContext3DCreate );
			_context3D = _stage3D.context3D;
			_context3D.enableErrorChecking = true;
			
			if( _createCallback != null ){
				_createCallback( this );
				_createCallback = null;
			}
		}
		
		/**
		 * 释放
		 */
		public function dispose():void{
			_createCallback = null;
			if( _stage3D ){
				_stage3D.removeEventListener( Event.CONTEXT3D_CREATE, _onContext3DCreate );
				_stage3D = null;
			}
			if( _context3D ){
				_context3D.dispose();
				_context3D = null;
			}
		}
		
		/**
		 * 绘制3D模型
		 */
		public function render( scene:Scene, vp:Matrix3D, passes:Array=null ):void{
			
			if(!passes) passes = preRender( scene );
			
			// 执行渲染
			_context3D.clear();
			_context3D.setCulling ( Context3DTriangleFace.NONE );
			_context3D.setDepthTest( true, Context3DCompareMode.LESS );	
			
			num_triangle = 0;
			num_pass = 0;
			const TIMES:int = 1;
			for each( var pass:IPass in passes ){
				var dp:DefaultPass = pass as DefaultPass;
				var world:Matrix3D = dp.world.clone();
				
				if( pass.activate( _context3D ) ){
					for(var t:int=0; t<TIMES; t++){
						num_triangle += pass.numTriangle;
						num_pass ++;
						pass.render( _context3D, vp );
						dp.world = world.clone();
						dp.world.prependTranslation(0, 0, t* 2);
						dp.world.prependRotation( t / 100 * 360, Vector3D.Y_AXIS );
					}
					pass.deactivate( _context3D );
				}
			}
			_context3D.present();
		}
		
		
		// 获取 passes
		public function preRender( scene:Scene ):Array{
			
			// 更新矩阵
			scene.updateWorldMatrix();
			
			// 搜索可渲染对象
			var passes:Array = [];
			scene.root.forEachAttachedObject( function(obj:MovableObject):void{
				var renderable:IRenderable = obj as IRenderable;
				if( renderable ){
					renderable.getRenderPasses( passes );
				}
			});
			
			return passes;
		}
	}
}